import { setCaptchaKey, setToken, setCookie, getAuthMsg } from '@/utils/authority';
import { getCaptchaImage, checkAccountOp, newCheckAccountOp, accountLogin, mobileLogin, findTokenOp } from './service';
import CryptoJS from 'crypto-js';
import { create } from "zustand";
import { Modal } from 'antd';

//解密方法
// function Decrypt(word) {
//   var key = CryptoJS.enc.Utf8.parse("zhaojiafangloginencrypti");
//   var decrypt = CryptoJS.AES.decrypt(word, key, {
//     mode: CryptoJS.mode.ECB,
//     padding: CryptoJS.pad.Pkcs7
//   });
//   return CryptoJS.enc.Utf8.stringify(decrypt).toString();
// }

const useLoginStore = create((set, get) => ({
	
	loading: false,

	loginInfo: {//登录信息
		username: '',
		password: '',
		code : '',
		mobile: undefined,
		sms_code: undefined,
		imgCaptcha: '',
	},

	checkInfo: {//御城河验证信息
		fid: '',
		phoneNumber: '',
		username: '',
		visible: false,
	},

	type: 'account',

	//切换type
	switchType: (val) => set({ type: val }),

	updateLoginInfo: (val) => set({ loginInfo: val }),

	//获取图片验证码
	getImgCaptcha: async () => {
		const res = await getCaptchaImage({ industrialBeltFlag: INDUSTRIAL_BELT_FLAG });
		const loginInfo = get().loginInfo;
		if(res.key) {
			set({ loginInfo: { ...loginInfo, imgCaptcha: res.image } });
			setCaptchaKey(res.key);
		}
	},

	//关闭御城河校验弹框
	cancelModal: () => set({
		checkInfo: {
			fid: '',
			phoneNumber: '',
			username: '',
			visible: false,
		}
	}),

	//校验账号-微信验证码登录
	newPreLogin: async (payload) => {
		const loginInfo = get().loginInfo;
		const { unionid, userId, mobile, sms_code, codeKey } = payload;
		set({ loginInfo: { ...loginInfo, unionid, userId, mobile, sms_code, codeKey }, loading: true })
		const params = {
			userId,
			mobile,
			grantType: unionid ? 3 : 2,
			code: unionid || sms_code || 'fixedValue',
		}
		const { success, data } = await newCheckAccountOp(params);
		if(success) {
			const { fid, isSuccess, phoneNumber, username } = data;
			if (isSuccess) {
				get().newLogin();
			} else {
				set({
					checkInfo: {
						fid,
						phoneNumber,
						username,
						visible: true,
						flag: true
					},
					loading: false
				})
			}
		}
	},

	//手机和微信登录
	newLogin: async () => {
		const loginInfo = get().loginInfo;
		const { unionid, userId, mobile, codeKey } = loginInfo;
		const { data, success } = await findTokenOp({
			unionid,
			mobile,
			codeKey,
			id: userId,
			type: unionid ? 1 : 0//类型：0:手机号登录, 1:微信登录,2:appleId登录
		});
		if(success) {
			const {tokenType, accessToken, isOldSystemUser, accountNo, isZjf } = data;
			//老用户提示不能登录
			if(isOldSystemUser !== 2) {
				Modal.info({
					title: '登录提示',
					content: '该账号没有登录权限，请联系实施开通。',
					okText: '知道了'
				});
				set({ loading: false });
				return;
			}
			const token = `${tokenType} ${accessToken}`;
			setToken(token);
			localStorage.setItem('isOldSystemUser', isOldSystemUser);
			localStorage.setItem('ACCOUNT_NO', accountNo);
			localStorage.setItem('ISZJF', isZjf);
			if(getAuthMsg()) {
				//如果存在授权信息，就跳转到网店列表页面
				location.href = '#/views/basic/qimenStore';
			} else {
				setCookie('needNotice', 1);
				location.href = '#/home';
			}
			set({ 
				loginInfo: {//登录信息
					username: '',
					password: '',
					code : '',
					mobile: undefined,
					sms_code: undefined,
					imgCaptcha: '',
				},
		
				checkInfo: {//御城河验证信息
					fid: '',
					phoneNumber: '',
					username: '',
					visible: false,
				},
				type: 'account',
				loading: false,
			})
		} else {
			set({ loading: false });
		}
	},

	//校验账号
	preLogin: async (payload) => {
		const { type } = payload;
		const loginInfo = get().loginInfo;
		let params;
		if(type == 'account') {
			const { username, password, code } = payload;
			set({
				loginInfo: {
					...loginInfo,
					username,
					password,
					code
				},
				loading: true,
			})
			params = {
				username: username.trim(),
				password: Encrypt(password.trim()),
				code: code.trim(),
				grantType:1
			}
		} else {
			const { prefix, mobile, sms_code } = payload;
			set({
				loginInfo: {
					...loginInfo,
					prefix,
					mobile,
					sms_code
				},
				loading: true,
			})
			params = {
				mobile: mobile.trim(),
				code: sms_code.trim(),
				grantType:2
			}
		}
		const { success, data } = await checkAccountOp(params);
		if (success) {
			const { fid, isSuccess, phoneNumber, username } = data;
			if(isSuccess) {
				get().login();
			} else {
				set({
					checkInfo: {
						fid,
						phoneNumber,
						username,
						visible: true,
					},
					loading: false,
				})
			}
		} else {
			if(type == 'account') {
				get().getImgCaptcha();
			}
			set({ loading: false });
		}
	},

	//登录页面
	login: async () => {
		const loginInfo = get().loginInfo;
		const type = get().type;
		let res;
		if(type == 'account') {
			const { username, password, code } = loginInfo;
			res = await accountLogin({
				username: username.trim(),
				password: Encrypt(password.trim()),
				code: code.trim(),
				industrialBeltFlag: INDUSTRIAL_BELT_FLAG
			});
		} else {
			const { mobile, sms_code, prefix } = loginInfo;
			res = await mobileLogin({
				mobile: mobile.trim(),
				sms_code: sms_code.trim(),
				prefix,
				industrialBeltFlag: INDUSTRIAL_BELT_FLAG,
			});
		}
		if(res.access_token) {
			const {token_type, access_token, is_old_system_user, account_no, is_zjf } = res;
			//老用户提示不能登录
			if(is_old_system_user !== 2) {
				Modal.info({
					title: '登录提示',
					content: '该账号没有登录权限，请联系实施开通。',
					okText: '知道了',
				});
				set({ loading: false });
				return;
			}
			localStorage.setItem('isOldSystemUser', is_old_system_user);
			localStorage.setItem('ACCOUNT_NO', account_no);
			const token = `${token_type} ${access_token}`;
			await setToken(token);
			localStorage.setItem('ISZJF', is_zjf);
			if(getAuthMsg()) {
				//如果存在授权信息，就跳转到网店列表页面
				location.href = '#/views/basic/qimenStore';
			} else {
				setCookie('needNotice', 1);
				location.href = '#/home';
			}
			set({
				loginInfo: {//登录信息
					username: '',
					password: '',
					code : '',
					mobile: undefined,
					sms_code: undefined,
					imgCaptcha: '',
				},
		
				checkInfo: {//御城河验证信息
					fid: '',
					phoneNumber: '',
					username: '',
					visible: false,
				},
				type: 'account',
				loading: false
			})
		} else {
			if(type == 'account') {
				set({
					checkInfo: {
						fid: '',
						phoneNumber: '',
						username: '',
						visible: false,
					},
					loading: false,
				})
				get().getImgCaptcha();
			} else {
				set({ loading: false });
			}
		}
	}
}))

//加密方法
function Encrypt(word) {
  var key = CryptoJS.enc.Utf8.parse("zhaojiafangloginencrypti");
  var srcs = CryptoJS.enc.Utf8.parse(word);
  var encrypted = CryptoJS.AES.encrypt(srcs, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  });
  return encrypted.toString();
}

export default useLoginStore;